﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.UI;
using NorthwindSample.Data;

namespace NorthwindSample.Controllers
{
    public class EmployeesController : Controller
    {
        //
        // GET: /Employees/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult EmployeeDetails()
        {
            return View("_EmployeeDetails");
        }

        public ActionResult GetEmployees([DataSourceRequest] DataSourceRequest request)
        {
            var employees = EmployeesRepository.GetEmployees().Select(e => new
            {
                EmployeeID = e.EmployeeID,
                LastName = e.LastName,
                FirstName = e.FirstName,
                FullName = string.Format("{0} {1} {2}", e.TitleOfCourtesy, e.FirstName, e.LastName),
                Title = e.Title,
                TitleOfCourtesy = e.TitleOfCourtesy,
                BirthDate = e.BirthDate,
                HireDate = e.HireDate,
                Address = e.Address,
                City = e.City,
                Region = e.Region,
                PostalCode = e.PostalCode,
                Country = e.Country,
                HomePhone = e.HomePhone,
                Extension = e.Extension,
                ReportsTo = e.ReportsTo
            }).ToList();

            return Json(new DataSourceResult { Data = employees });
        }

        [HttpPost]
        public JsonResult SaveEmployee(Employee employee)
        {
            bool success = false;
            string error = string.Empty;

            try
            {
                success = EmployeesRepository.SaveEmployee(employee);
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            return Json(new { success = success, error = error }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult DeleteEmployee(int id)
        {
            bool success = false;
            string error = string.Empty;

            try
            {
                success = EmployeesRepository.DeleteEmployee(id);
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            return Json(new { success = success, error = error }, JsonRequestBehavior.AllowGet);
        }
    }
}
